
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
requests.packages.urllib3.disable_warnings()  # Disable warning message


class BasicOperation(object):
    """ An object to provide easy RESTful request operations for DNAC"""

    def __init__(self, host,username,
                 password,version='v1',**kwargs):

        self.__dict__.update(kwargs)
        self.api_url = "https://%s/api/%s/%s" # host, version and api
        self.host = host
        self.version = version
        self.username = username
        self.password = password
        self.headers = {"content-type":"application/json"}

        if self.username is not None:
            self.get_X_auth_token()
        else:
            print ("need to provide username")

    def get_X_auth_token(self):

        r_json = HTTPBasicAuth(self.username, self.password)
        # Post ticket API request
        try:
            r = requests.post("https://"+self.host+"/dna/system/api/"+ self.version +"/auth/token",auth=r_json,headers=self.headers,verify = False)
            response_json = r.json()

            # Adding 'X-Auth-Token' to header
            self.headers['X-Auth-Token'] = response_json["Token"]
            return (response_json["Token"])
        except:
            # Something wrong, cannot get service ticket
            print ("Status: %s"%r.status_code)
            print ("Response: %s"%r.text)
            sys.exit ()


    def get_url(self, api):

        complete_url = self.api_url % (self.host, self.version, api)
        return complete_url

    def get(self, api, params='', printOut=False):

        try:
            url = self.get_url(api)
            if printOut:
                print ("\nExecuting GET '%s'\n"%url)
            r = requests.get(url,headers=self.headers,params=params, verify = False)
            print ("GET '%s' Status: "%api,r.status_code,'\n') # This is the http request status
            if printOut:
                self.prettyPrint("Response:\n", r)
            return r.json()
        except:
            print ("Something wrong to GET /",api)
            sys.exit()

    def post(self,api,data=None,params='',printOut=False):

        try:
            url = self.get_url(api)
            if printOut:
                print ("\nExecuting POST '%s'\n"%url)
            r = requests.post(url, json.dumps(data), headers=self.headers,params=params,verify = False)
            print ("POST '%s' Status: "%api,r.status_code,'\n') # This is the http request status
            if printOut:
                self.prettyPrint("Response:\n", r)
            return r.json()
        except:
            print ("Something wrong to POST /",api)
            sys.exit()

    def put(self, api, data=None, printOut=False):

        try:
            url = self.get_url(api)
            if printOut:
                print ("\nExecuting PUT '%s'\n"%url)
            r = requests.put(url, data, headers=self.headers,verify = False)
            print ("PUT '%s' Status: "%api,r.status_code,'\n') # This is the http request status
            if printOut:
                self.prettyPrint("Response:\n", r)
            return r.json()
        except:
            print ("Something wrong to PUT /",api)
            sys.exit()

    def delete(self, api, params='',printOut=False):

        try:
            url = self.get_url(api)
            if printOut:
                print ("\nExecuting DELETE '%s'\n"%url)
            r = requests.delete(url, headers=self.headers, params=params, verify = False)
            print ("DELETE '%s' Status: "%api,r.status_code,'\n') # This is the http request status
            if printOut:
                self.prettyPrint("Response:\n", r)
            return r.json()
        except:
            print ("Something wrong to DELETE /",api)
            sys.exit()

    def prettyPrint(self,text="",json_dict=None):

        print (text,json.dumps(json_dict,indent=4))

